import { ref } from 'vue'
import type { LogMessage } from '../../types'

// 日志管理器
export default class LogService {
  public logs = ref<LogMessage[]>([])

  // 添加日志
  addLog(msg: string, type: LogMessage['type'] = 'info') {
    const timestamp = new Date()
    const currentTime = timestamp.toLocaleTimeString()

    const log: LogMessage = {
      msg,
      type,
      timestamp: timestamp,
      time: currentTime,
    }
    // 添加到日志数组
    this.logs.value.unshift(log)

    // 限制日志数量，避免内存占用过大
    if (this.logs.value.length > 500) {
      // 删除最早的trimCount条日志
      this.logs.value.splice(this.logs.value.length - 100)
    }

    return log
  }

  // 添加信息日志
  info(message: string) {
    return this.addLog(message, 'info')
  }

  // 添加成功日志
  success(message: string) {
    return this.addLog(message, 'success')
  }

  // 添加警告日志
  warning(message: string) {
    return this.addLog(message, 'warning')
  }

  // 添加错误日志
  error(message: string) {
    return this.addLog(message, 'error')
  }

  // 清空日志
  clear() {
    this.logs.value = []
  }

  // 根据类型过滤日志
  filterByType(type: LogMessage['type']) {
    return this.logs.value.filter((log) => log.type === type)
  }
}
